package site.yaoer.dongbao.ums.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import site.yaoer.dongbao.ums.common.base.annotations.TokenCheck;
import site.yaoer.dongbao.ums.common.base.result.ResultWrapper;
import site.yaoer.dongbao.ums.entity.UmsMember;
import site.yaoer.dongbao.ums.entity.dto.UmsMemberHelloDTO;
import site.yaoer.dongbao.ums.entity.dto.UmsMemberLoginDTO;
import site.yaoer.dongbao.ums.entity.dto.UmsMemberRegisterDTO;
import site.yaoer.dongbao.ums.mapper.UmsMemberMapper;
import site.yaoer.dongbao.ums.service.UmsMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import site.yaoer.dongbao.ums.utils.JwtUtils;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author 傅俊
 * @since 2021-07-07
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    @Autowired
    UmsMemberMapper umsMemberMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public ResultWrapper register(UmsMemberRegisterDTO umsMemberRegisterDTO) {
        UmsMember umsMember = new UmsMember();
        BeanUtils.copyProperties(umsMemberRegisterDTO, umsMember);

        umsMember.setPassword(passwordEncoder.encode(umsMember.getPassword()));

        umsMemberMapper.insert(umsMember);

        return ResultWrapper.getSuccessBuilder().build();
    }

    @Override
    public ResultWrapper login(UmsMemberLoginDTO umsMemberLoginDTO) {
        UmsMember umsMember = umsMemberMapper.selectByName(umsMemberLoginDTO.getUsername());

        String password = umsMemberLoginDTO.getPassword();
        boolean isMatch = passwordEncoder.matches(password, umsMember.getPassword());

        if (isMatch) {
            String token = JwtUtils.createToken(umsMemberLoginDTO.getUsername());
            return ResultWrapper.builder().code(200).msg("登录成功").data(token).build();
        } else {
            return ResultWrapper.getFailBuilder().build();
        }
    }

    @Override
    public ResultWrapper hello(UmsMemberHelloDTO helloDTO) {
        // 判断是否有token
        return ResultWrapper.builder().code(200).msg("业务处理成功").data("Hello, " + helloDTO.getUsername() + ";" + helloDTO.getMessage()).build();
    }
}
